#ifndef YANIMATIONBASE_H
#define YANIMATIONBASE_H

#include "Entity.h"

namespace Y{

class AnimationBase: public Entity{

	public:
		std::vector< AnimationBase* > tails;
		float counter;
		float endCount;
		float speed;
		float tickCounter;
		bool started;
		bool active;

	public:
		
		AnimationBase( Entity *parentis = NULL ):
			Entity(parentis),
			counter(0.0),
			endCount(0.0),
			started(false),
			speed(1.0),
			tickCounter(0.0),
			active(false)
		{
			configure(
				C( signal, "finished" ),
				C( signal, "started" ),
				C( signal, "killed" ),
				C( signal, "tick" )
			);
		}
		
		virtual ~AnimationBase(){
			for ( int i = 0; i < tails.size(); ++i ){
				delete tails[i];
			}
		}
		
		virtual void die (){
			call( "killed" );
			Entity::die();
		}
		
		virtual void handleConfig ( ConfigVector& cv ){
			for ( int i = 0; i < cv.size(); ++i ){
				if ( cv[i].name == "speed" ){ speed = cv[i].to<float>();handled(); }
				else if ( cv[i].name == "end count" || cv[i].name == "limit" ){ endCount = cv[i].to<float>();handled(); }
				else if ( cv[i].name == "tail" || cv[i].name == "add tail" ){ tails.push_back( cv[i].to< AnimationBase *>() );handled(); }
			}
			Entity::handleConfig(cv);
		}
		
		virtual void timer (float f){
			if ( active ){
				bool b = tick(f * speed);
				call ( "tick" );
				if ( ! b ){
					end();
					die();
				}
				counter += f * speed;
				tickCounter += 1.0;
			}
		}
		
		virtual void addTail ( AnimationBase *t ){ tails.push_back( t ); }
		
		virtual bool tick (float t = 1.0){ return true; }
		virtual void activate (){ if ( !started ){ start(); }    active = true; }
			virtual void start() { counter = 0.0; started = true; call("started"); }
			virtual void end  () { 
				for ( int i = 0; i < tails.size(); ++i ){ tails[i]->activate(); } tails.clear(); call("finished"); 
			}
		virtual void deactivate () { active = false; }
};


}
#endif
